<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Users;
use App\Models\Linkslists;
use App\Models\Linkslistssetting;
use App\Models\Memberorders;
use App\Models\Usersinvitations;
use App\Models\Linkslistsqrcodes;
use App\Services\CommonService;
use App\Services\WechatService;
use App\Services\WechatoffiaccountService;
use App\Services\CacheService;
use App\Services\OutputService;
use App\Models\Linkslistsminapps;
use Exception,Cookie,Log;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class WebController extends Controller
{
    public function articleDetial(Request $request,$links_id)
    {
        header('Access-Control-Allow-Origin: *');
        $sign = CommonService::md5Encrypt($links_id);
        if ($sign != $request->sign) return response()->json(['status' => 'error', 'msg' => '签名错误！']);

        if(Cache::has('links_api_'.$links_id)) {
            $links = Cache::get('links_api_'.$links_id);
        } else {
            $links = Linkslists::jumpGetApiLinks($links_id);
            if (empty($links)) return OutputService::error("您访问的链接不存在！");
            if ($links->disable != 1) return OutputService::error("链接已删除！");
            if (!in_array($links["platfrom_type"], [8,9,11,12])) return OutputService::error("链接错误！");
            if ($links->limit_status == 1 && $links->left_pv <= 0) return OutputService::error("链接访问次数不足,请充值！");
            if ($links->limit_pv > 1000 && $links->end_time < time()) return OutputService::error("会员已过期,请续费后访问充值！");
            if ($links->limit_pv < 1000 && $links->end_time < time()) return OutputService::error("免费体验已过期1小时,请开通会员后访问！");
            // 获取小程序内样式
            $linksSetting = Linkslistssetting::getLinksListsSetting($links_id);
            $links = collect($links)->merge($linksSetting)->all();
            // 每次调用缓存30分钟
            Cache::put('links_api_'.$links_id, $links, 1800);
        }

        if (in_array($links["platfrom_type"], [8,9,11,12])) {
            $batch = date("Ymd");
            $qrcodes = Redis::hget("links_qrcodes_".$batch, $links_id);
            if (empty($qrcodes)) {
                // 更新昨天二维码数据并且删除缓存
                CacheService::removeLinksQrcodeCache($links_id,date("Ymd",strtotime("-1 day")));
                $qrcodes = Linkslistsqrcodes::getAllLinksListsQrcodes($links_id);
                if (empty($qrcodes)) return OutputService::error("当前暂无二维码！");
                Redis::hset("links_qrcodes_".$batch, $links_id, json_encode($qrcodes));
            } else {
                $qrcodes = json_decode($qrcodes);
            }
            if (empty($qrcodes)) return OutputService::error("当前暂无二维码！");
            $qrcode_image = "";
            if ($links["qrcode_switch"] == 2){
                // 随机二维码
                $key = rand(0,count($qrcodes)-1);
                $qrcodes[$key]->scan_total += 1;
                $qrcodes[$key]->scan_today += 1;
                $qrcode_image = $qrcodes[$key]->img_url;
            } else {
                $qrcodes = collect($qrcodes);
                if ($links["qrcode_switch"] == 1) {
                    // 顺序切换
                    $qrcodes = $qrcodes->sortByDesc('rate')->all();
                } else {
                    // 循环切换
                    $qrcodes = $qrcodes->sortBy('scan_today')->all();
                }
                foreach ($qrcodes as $key => $qrcode) {
                    if ($links["qrcode_upper"] == 1) {
                        // 累计上限
                        if ($qrcode->scan_total < $qrcode->count_limit) {
                            $qrcodes[$key]->scan_total += 1;
                            $qrcodes[$key]->scan_today += 1;
                            $qrcode_image = $qrcode->img_url;
                            break;
                        }
                    } else {
                        // 每日上限
                        if ($qrcode->scan_today < $links["qrcode_daily"]) {
                            $qrcodes[$key]->scan_total += 1;
                            $qrcodes[$key]->scan_today += 1;
                            $qrcode_image = $qrcode->img_url;
                            break;
                        }
                    }
                }
            }
            if (empty($qrcode_image)) return OutputService::error("当前暂无二维码！");
            Redis::hset("links_qrcodes_".$batch, $links_id, json_encode($qrcodes));
        }

        $nlinks = ["title"=>"二维码详情","miniapp_style"=>$links["miniapp_style"],"qrcode_notice"=>$links["qrcode_notice"],"logo"=>$links["logo"],"nike"=>$links["nike"],"describe"=>$links["describe"],"platfrom_type"=>$links["platfrom_type"],"qrcodes_img_url"=>$qrcode_image];
        return OutputService::success("Success",$nlinks);
    }

    public function linksDetial(Request $request,$links_id)
    {
        header('Access-Control-Allow-Origin: *');
        $sign = CommonService::md5Encrypt($links_id);
        if ($sign != $request->sign) {
            Log::info($request->all());
            Log::info($sign);
            return response()->json(['status' => 'error', 'msg' => '签名错误！']);
        }
        if(Cache::has('links_id_'.$links_id)) {
            $links = Cache::get('links_id_'.$links_id);
        } else {
            $links = Linkslists::getLinks($links_id);
            // 每次调用缓存30分钟
            Cache::put('links_id_'.$links_id, $links, $seconds = 1800);
        }
        if (empty($links)) return response()->json(['status' => 'error', 'msg' => '链接不存在,请核实链接是否正确!']);
        if ($links->users_id == 7) {
            if (empty($request->token)) return response()->json(['status' => 'error', 'msg' => '演示链接不存在,请重新获取链接！']);
            $token = CommonService::aesDncrypt($request->token);
            if ($token <= time()) return response()->json(['status' => 'error', 'msg' => '链接已过期,请重新获取链接！']);
        }
        if ($links->disable == 2) return response()->json(['status' => 'error', 'msg' => '链接已被删除!']);
        if ($links->limit_status == 1 && $links->left_pv < 1) return response()->json(['status' => 'error', 'msg' => '链接访问量不足,请升级VIP！']);
        if ($links->limit_pv >= 10000 && $links->end_time < time()) return response()->json(['status' => 'error', 'msg' => '链接已过期,请续费后访问!']);
        if ($links->end_time < time()) return response()->json(['status' => 'error', 'msg' => '免费链接仅在60分钟内有效,已过期！']);
        if (empty($links->urlscheme)) return response()->json(['status' => 'error', 'msg' => '链接异常,请重新创建！']);
        $linksArray = ["title"=>$links->title,"logo"=>$links->logo,"urlscheme"=>$links->urlscheme,"qrcodes"=>$links->qrcodes,"redirect_style"=>$links->redirect_style,"platfrom_type"=>$links->platfrom_type,"msg"=>$links->msg,"links_id"=>$links->links_id,"end_time"=>$links->end_time,"original_id"=>$links->original_id,"path"=>$links->path,"styles"=>$links->styles,"type"=>$links->type];
        return response()->json(['status' => 'success', 'msg' => '数据获取成功！', 'links'=>$linksArray]);
    }

    public function shortTimeLinksDetial(Request $request,$links_id)
    {
        header('Access-Control-Allow-Origin: *');
        $sign = CommonService::md5Encrypt($links_id);
        if ($sign != $request->sign) return response()->json(['status' => 'error', 'msg' => '签名错误！']);
        $links = Linkslists::getLinks($links_id);
        if(empty($links)) return response()->json(['status' => "error", 'code' => "1001", 'msg' => "链接不存在,请核实链接是否正确！"]);
        if ($links->disable == 2) return response()->json(['status' => 'error', 'msg' => '链接已被删除!']);
        if ($links->limit_status == 1 && $links->left_pv < 1) return response()->json(['status' => 'error', 'msg' => '链接访问量不足,请升级VIP！']);
        if ($links->limit_pv >= 10000 && $links->end_time < time()) return response()->json(['status' => 'error', 'msg' => '链接已过期,请续费后访问!']);
        if ($links->end_time < time()) return response()->json(['status' => 'error', 'msg' => '免费链接仅在60分钟内有效,已过期！']);
        $mini_id = "";
        $urlscheme = "";
        if($links->platfrom_type == 4){
            $msg = $links->msg;
            $msg=json_decode($msg,true);
            $mini_id = $msg["mini_id"];
            if(empty($mini_id)) return response()->json(['status' => "error", 'code' => "1003", 'msg' => "小程序AppID不存在,请联系客服！"]);
            $minapps = Linkslistsminapps::getLinksListsMinappsByAppid($mini_id);
            if(empty($mini_id)) return response()->json(['status' => "error", 'code' => "1004", 'msg' => "该链接创建的小程序未在天天外链后台查询到，请先添加！"]);
            $minpath = str_replace("&amp;","&",$request->path);
            if(empty($minpath)) {
                $path = "";
                $query = "";
            }else{
                $minpaths = parse_url(urldecode($minpath));
                $path = isset($minpaths["path"]) ? $minpaths["path"] : "";
                $query = isset($minpaths["query"]) ? $minpaths["query"] : "";
            }
            $getShortTimeUrlScheme = WechatService::shortTimeUrl($minapps->appid,$minapps->secret,$path,$query);
            if ($getShortTimeUrlScheme["status"] == "error") return response()->json(['status' => 'error',"code"=>"1001", 'msg' => $getShortTimeUrlScheme["msg"]]);
            $urlscheme = $getShortTimeUrlScheme["urlscheme"];
        }else{
            $urlscheme = $links->urlscheme;
            if (empty($urlscheme)) return response()->json(['status' => 'error', 'msg' => '链接异常,请重新创建！']);
        }
        $linksArray = ["title"=>$links->title,"logo"=>$links->logo,"urlscheme"=>$urlscheme,"qrcodes"=>$links->qrcodes,"redirect_style"=>$links->redirect_style,"platfrom_type"=>$links->platfrom_type,"msg"=>$links->msg,"links_id"=>$links->links_id,"end_time"=>$links->end_time,"original_id"=>$links->original_id,"path"=>$links->path,"styles"=>$links->styles,"type"=>$links->type];
        return response()->json(['status' => 'success', 'msg' => '数据获取成功！', 'links'=>$linksArray]);
    }

    public function loginQrcode(Request $request)
    {
        try {
            $offiacApp = WechatoffiaccountService::officialAccount();
            $time = time();
            $token = md5($_SERVER["REMOTE_ADDR"].time().rand(10000,99999));
            $sign = md5($token.$time.$token."sign");
            $result = $offiacApp->qrcode->temporary("login-".$token, 600);
            $qrcodeurl = $offiacApp->qrcode->url($result["ticket"]);
        } catch (Exception $e) {
            $time = "";
            $token = "";
            $sign = "";
            $qrcodeurl = "";
            return response()->json(['status' => 'error', 'msg' => '二维码获取失败']);
        }
        return response()->json(['status' => 'success', 'msg' => '二维码获取成功！', 'data'=>['token'=>$token,'time'=>$time,'sign'=>$sign,'qrcodeurl'=>$qrcodeurl]]);

    }
}
